﻿using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NetC100K;
using NetC100KHost.Command;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;

namespace NetC100KHost
{
    internal class TimedHostedService : IHostedService
    {
        private ILogger _logger;
        private ServerPool _service;
        private CancellationTokenSource _cts;

        public TimedHostedService(ServerPool service, ILogger<TimedHostedService> logger)
        {
            _service = service;
            _logger = logger;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _cts = new CancellationTokenSource();
            Task.Run(async () =>
              {
                  while (!_cts.IsCancellationRequested)
                  {
                      await Task.Delay(30 * 1000);

                      _logger.LogInformation("定时数据开始发送......");
                      var options = new System.Text.Json.JsonSerializerOptions()
                      {
                          Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                      };
                      _service.ConcurrentSend((channel) =>
                      {
                          PushResponse response = new PushResponse()
                          {
                              Datetime = DateTime.Now,
                              Message = "汉字测试"
                          };
                          return JsonSerializer.Serialize<PushResponse>(response, options);
                      });
                      _logger.LogInformation($"定时数据发送完成，现有连接数：{_service.Channels.Count}......");
                  }
              }, _cts.Token);
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }
}
